package cn.usbtg.poi.ext.download.dataloader;

import cn.usbtg.poi.ext.download.bean.POITitle;
import cn.usbtg.poi.ext.download.celltheme.POICellTheme;
import cn.usbtg.poi.ext.download.celltheme.POICellThemeDefault;
import cn.usbtg.sutil.EmptyUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * json数据加载器
 */
public class POIDataLoaderJson implements POIDataLoader {

    @Override
    public void load(Sheet sheet, List<POITitle> titles, List datas, int beginRow, int endRow) {
        if (EmptyUtil.isEmpty(datas)) return;
        beginRow = EmptyUtil.isNotEmpty(beginRow) ? beginRow : 0;
        endRow = EmptyUtil.isNotEmpty(endRow) ? endRow : datas.size();
        beginRow = beginRow >= 0 ? beginRow : 0;
        endRow = endRow <= datas.size() ? endRow : datas.size();

        boolean hasTitle = false; //是否拥有标题行
        if (EmptyUtil.isNotEmpty(titles)) {
            hasTitle = true;
        } else { //若没有设置标题行，遍历数据集依次导出
            titles = new ArrayList<POITitle>();

            JSONObject firstRow = (JSONObject) datas.get(0);
            Iterator<String> iterator = firstRow.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                titles.add(new POITitle(key, key));
            }
        }

        CellStyle cellStyleDefault = new POICellThemeDefault().theme(sheet.getWorkbook()); //默认单元格样式
        List<CellStyle> cellThemes = new ArrayList<CellStyle>();
        for (int j = 0; j < titles.size(); j++) {
            POITitle title = titles.get(j);
            POICellTheme cellTheme = title.getCellStyleData();
            cellThemes.add(EmptyUtil.isNotEmpty(cellTheme) ? cellTheme.theme(sheet.getWorkbook()) : cellStyleDefault);
        }

        int titleRow = hasTitle ? 1 : 0;
        int rowNum = titleRow;
        for (int i = beginRow; i < endRow; i++) {
            JSONObject rowJson = (JSONObject) datas.get(i);

            Row row = sheet.createRow(rowNum++);
            for (int j = 0; j < titles.size(); j++) {
                POITitle title = titles.get(j);
                Cell cell = row.createCell(j);
                cell.setCellStyle(cellThemes.get(j));
                cell.setCellValue(rowJson.getString(title.getCode()));
            }
        }
    }
}